#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


#define SIZE 1024
#define MAX_ARGC 64
#define SEP " "

char* argv[MAX_ARGC];
char pwd[SIZE];

const char* HostName()
{
    char* hostname = getenv("HOSTNAME");
    if(hostname) return hostname;
    else return "None";
}

char* Home()
{
    return getenv("HOME");
}

const char* UserName()
{
    char* username = getenv("USER");
    if(username) return username;
    else return "None";

}

const char* Currentworkdir()
{
    char*pwd = getenv("PWD");
    if(pwd) return pwd;
    else return "None";
}

int interactive(char* out,int size)
{
    printf("[%s@%s %s]$ ",UserName(),HostName(),Currentworkdir());
    fgets(out,size,stdin);
    out[strlen(out)-1] = '\0';
    return strlen(out);
}

void split(char* in)
{
    int i = 0;
    argv[i++] = strtok(in,SEP);
    while(argv[i++] = strtok(NULL,SEP));
}

void Execute()
{

    pid_t id = fork();
    if(id == 0)
    { 
        execvp(argv[0],argv);
        exit(1);
    }
    
    waitpid(id,NULL,0);

    //printf("run done rid:%d\n",rid);
}

int BuildinCmd()
{
    int ret = 0;
    if(strcmp("cd",argv[0]) == 0)
    {
        ret = 1;
        char* target = argv[1];
        if(!target) target = Home();
        chdir(target);
        char temp[SIZE];
        getcwd(temp,SIZE);
        snprintf(pwd,SIZE,"PWD=%s",temp);
        putenv(pwd);
    }
    return ret;
}

int main()
{
    while(1)
    {
        char commandline[SIZE];
        int n =  interactive(commandline,SIZE);
        if(n == 0) continue;

        split(commandline);
        
        n = BuildinCmd();
        if(n) continue;

        Execute();
    }
    return 0;
}


